package com.huatai.bi.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huatai.bi.entity.DatasourceEntity;
import com.huatai.bi.query.DatasourceQuery;
import com.huatai.bi.service.DatasourceService;
import com.huatai.bi.service.TableService;
import com.huatai.common.api.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@Api(value = "数据库连接信息",tags = "数据库连接")
@RequestMapping("/datasource")
public class DatasourceController {

    @Autowired
    DatasourceService service;
    @Autowired
    TableService tableService;

    @GetMapping("/get/{id}")
    @ApiOperation(value = "根据ID获取数据")
    public R<DatasourceEntity> get(@PathVariable("id") Long id){
        DatasourceEntity entity = service.getById(id);
        if(null == entity){
            return R.fail("获取数据失败，记录不存在");
        }
        return R.data(entity);
    }

    @PostMapping("/page")
    @ApiOperation(value = "获取列表-分页")
    public R<Page> Page(@RequestBody DatasourceQuery query){
        return R.data(service.page(query));
    }

    @PostMapping("/list")
    @ApiOperation(value = "获取列表")
    public R<List<DatasourceEntity>> list(){
        return R.data(service.list());
    }

    @PostMapping("/save")
    @ApiOperation(value = "新增或修改")
    public R save(@Valid @RequestBody DatasourceEntity entity){
        return R.data(service.saveOrUpdate(entity));
    }


    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据ID删除记录")
    public R delete(@PathVariable("id") Long id){
        return R.data(service.removeById(id));
    }

    @PostMapping("/connect")
    @ApiOperation(value = "测试连接")
    public R connect(@Valid @RequestBody DatasourceEntity entity){
        service.connect(entity);
        return R.data(null);
    }

    @PostMapping("/getSchema")
    @ApiOperation(value = "获取模式")
    public R getSchema(@Valid @RequestBody DatasourceEntity entity){
        return R.data(service.getSchema(entity));
    }

    @GetMapping("/refreshDict/{id}")
    @ApiOperation(value = "刷新字段数据")
    public R refreshDict(@PathVariable("id") Long id){
        tableService.updateByDatasourceId(id);
        return R.data(null);
    }
}
